
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户管理系统</title>
  <!-- 引入Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- 引入Font Awesome图标 -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f8f9fa;
    }
    .container {
      max-width: 1200px;
      margin-top: 30px;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
      padding: 25px;
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }
    .search-form {
      background-color: #f8f9fa;
      padding: 15px;
      border-radius: 5px;
      margin-bottom: 20px;
    }
    .table th {
      background-color: #f1f3f5;
      color: #495057;
    }
    .action-buttons .btn {
      margin-right: 5px;
      margin-bottom: 5px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
    .modal-content {
      border-radius: 10px;
    }
    .form-label {
      font-weight: 500;
    }
    .password-note {
      font-size: 0.8rem;
      color: #6c757d;
      margin-top: 0.25rem;
    }
    /* 分配角色相关样式 */
    .btn-role {
      background-color: #0dcaf0;
      border-color: #0dcaf0;
      color: white;
    }
    .btn-role:hover {
      background-color: #0bb6d9;
      border-color: #0aa8c7;
    }
    #currentRole {
      padding: 8px;
      background-color: #f8f9fa;
      border-radius: 4px;
      min-height: 38px;
    }
    .alert-message {
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 1100;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="header">
    <h2><i class="fas fa-users me-2"></i>用户管理系统</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal" onclick="openAddModal()">
      <i class="fas fa-plus me-1"></i>新增用户
    </button>
  </div>

  <!-- 搜索表单 -->
  <div class="search-form">
    <div class="row">
      <div class="col-md-4">
        <input type="text" id="searchUserName" class="form-control" placeholder="请输入用户名">
      </div>
      <div class="col-md-2">
        <button class="btn btn-outline-primary" onclick="loadUsers()">
          <i class="fas fa-search me-1"></i>搜索
        </button>
        <button class="btn btn-outline-secondary" onclick="resetSearch()">
          <i class="fas fa-undo me-1"></i>重置
        </button>
      </div>
    </div>
  </div>

  <!-- 用户表格 -->
  <div class="table-responsive">
    <table class="table table-hover table-bordered">
      <thead class="table-light">
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>身份证号</th>
        <th>联系电话</th>
        <th>邮箱</th>
        <th>居住地址</th>
        <th>当前角色</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody id="userTableBody">
      <!-- 数据将通过JavaScript动态加载 -->
      </tbody>
    </table>
  </div>

  <!-- 分页控件 -->
  <div class="pagination-container">
    <nav aria-label="Page navigation">
      <ul class="pagination" id="pagination">
        <!-- 分页将通过JavaScript动态生成 -->
      </ul>
    </nav>
  </div>

  <!-- 新增/编辑用户模态框 -->
  <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="userModalLabel">新增用户</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="userForm">
            <input type="hidden" id="userId">
            <div class="row mb-3">
              <div class="col-md-6">
                <label for="userName" class="form-label">用户名</label>
                <input type="text" class="form-control" id="userName" required>
              </div>
              <div class="col-md-6">
                <label for="pid" class="form-label">身份证号</label>
                <input type="text" class="form-control" id="pid">
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <label for="mobile" class="form-label">联系电话</label>
                <input type="text" class="form-control" id="mobile">
              </div>
              <div class="col-md-6">
                <label for="email" class="form-label">邮箱</label>
                <input type="email" class="form-control" id="email">
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-12">
                <label for="address" class="form-label">居住地址</label>
                <input type="text" class="form-control" id="address">
              </div>
            </div>
            <div class="row mb-3">
              <div class="col-md-6">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password">
                <div class="password-note">编辑用户时，留空表示不修改密码</div>
              </div>
              <div class="col-md-6">
                <label for="confirmPassword" class="form-label">确认密码</label>
                <input type="password" class="form-control" id="confirmPassword">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 分配角色模态框 -->
  <div class="modal fade" id="assignRoleModal" tabindex="-1" aria-labelledby="assignRoleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="assignRoleModalLabel">分配角色</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="assignRoleForm">
            <input type="hidden" id="assignUserId">
            <div class="mb-3">
              <label for="roleSelect" class="form-label">选择角色</label>
              <select class="form-select" id="roleSelect">
                <!-- 角色选项将通过JavaScript动态加载 -->
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">当前角色</label>
              <div id="currentRole" class="text-muted">
                <!-- 当前角色信息将通过JavaScript动态加载 -->
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" onclick="assignRole()">确认分配</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 引入必要的JS库 -->
<script src="js/user/jquery.min.js"></script>
<script src="js/user/bootstrap.js"></script>

<script>
  // 全局变量
  let currentPage = 1;
  const pageSize = 10;
  let userModal = new bootstrap.Modal(document.getElementById('userModal'));
  let roleModal = new bootstrap.Modal(document.getElementById('assignRoleModal'));
  let allRoles = []; // 存储所有角色数据

  // 页面加载时初始化数据
  $(document).ready(function() {
    loadRoles();
    loadUsers();
  });

  // 加载用户数据
  function loadUsers(page = 1) {
    currentPage = page;
    const userName = $('#searchUserName').val();

    $.ajax({
      url: '/sysUser/pageUser',
      method: 'GET',
      data: {
        userName: userName,
        pageSize: pageSize,
        current: page
      },
      success: function(response) {
        renderTable(response.records);
        renderPagination(response.current, response.pages);
      },
      error: function() {
        showAlert('danger', '加载用户数据失败，请稍后重试');
      }
    });
  }

  // 加载所有角色数据
  function loadRoles() {
    $.ajax({
      url: '/sysUser/getAllRole',
      method: 'GET',
      success: function(response) {
        if (response.success) {
          allRoles = response.data;
        } else {
          showAlert('danger', response.message || '加载角色列表失败');
        }
      },
      error: function() {
        showAlert('danger', '加载角色列表失败');
      }
    });
  }

  // 渲染表格数据
  function renderTable(users) {
    const tbody = $('#userTableBody');
    tbody.empty();

    if (users.length === 0) {
      tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
      return;
    }

    // 先渲染用户数据，然后为每个用户加载角色信息
    users.forEach(user => {
      const row = $(`
        <tr>
          <td>${user.userId}</td>
          <td>${user.userName}</td>
          <td>${user.pid || '-'}</td>
          <td>${user.mobile || '-'}</td>
          <td>${user.email || '-'}</td>
          <td>${user.address || '-'}</td>
          <td id="role-${user.userId}">加载中...</td>
          <td class="action-buttons">
            <button class="btn btn-sm btn-warning" onclick="openEditModal(${user.userId})">
              <i class="fas fa-edit"></i> 编辑
            </button>
            <button class="btn btn-sm btn-role" onclick="openAssignRoleModal(${user.userId})">
              <i class="fas fa-user-tag"></i> 分配角色
            </button>
            <button class="btn btn-sm btn-danger" onclick="confirmDelete(${user.userId})">
              <i class="fas fa-trash-alt"></i> 删除
            </button>
          </td>
        </tr>
      `);
      tbody.append(row);

      // 加载用户角色信息
      loadUserRoleForTable(user.userId);
    });
  }

  // 为表格中的用户加载角色信息
  function loadUserRoleForTable(userId) {
    $.ajax({
      url: '/sysUser/getRoleByUserId',
      method: 'GET',
      data: { userId: userId },
      success: function(response) {
        const roleCell = $(`#role-${userId}`);
        if (response.success) {
          if (response.data) {
            // 查找角色名称
            const role = allRoles.find(r => r.roleId === response.data);
            roleCell.text(role ? role.roleName : '未知角色');
          } else {
            roleCell.text('未分配角色');
          }
        } else {
          roleCell.text('加载失败');
        }
      },
      error: function() {
        $(`#role-${userId}`).text('加载失败');
      }
    });
  }

  // 渲染分页
  function renderPagination(current, totalPages) {
    const pagination = $('#pagination');
    pagination.empty();

    if (totalPages <= 1) return;

    // 上一页按钮
    pagination.append(`
      <li class="page-item ${current === 1 ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="loadUsers(${current - 1})">
          <i class="fas fa-angle-left"></i>
        </a>
      </li>
    `);

    // 页码按钮
    const startPage = Math.max(1, current - 2);
    const endPage = Math.min(totalPages, current + 2);

    if (startPage > 1) {
      pagination.append('<li class="page-item disabled"><a class="page-link">...</a></li>');
    }

    for (let i = startPage; i <= endPage; i++) {
      pagination.append(`
        <li class="page-item ${i === current ? 'active' : ''}">
          <a class="page-link" href="#" onclick="loadUsers(${i})">${i}</a>
        </li>
      `);
    }

    if (endPage < totalPages) {
      pagination.append('<li class="page-item disabled"><a class="page-link">...</a></li>');
    }

    // 下一页按钮
    pagination.append(`
      <li class="page-item ${current === totalPages ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="loadUsers(${current + 1})">
          <i class="fas fa-angle-right"></i>
        </a>
      </li>
    `);
  }

  // 打开新增用户模态框
  function openAddModal() {
    $('#userModalLabel').text('新增用户');
    $('#userForm')[0].reset();
    $('#userId').val('');
    $('#password').attr('required', true);
    $('#confirmPassword').attr('required', true);
    userModal.show();
  }

  // 打开编辑用户模态框
  function openEditModal(userId) {
    const user = getUserFromTable(userId);

    if (user) {
      $('#userModalLabel').text('编辑用户');
      $('#userId').val(user.userId);
      $('#userName').val(user.userName);
      $('#pid').val(user.pid);
      $('#mobile').val(user.mobile);
      $('#email').val(user.email);
      $('#address').val(user.address);
      $('#password').val('').removeAttr('required');
      $('#confirmPassword').val('').removeAttr('required');
      userModal.show();
    } else {
      showAlert('danger', '获取用户信息失败');
    }
  }

  // 打开分配角色模态框
  function openAssignRoleModal(userId) {
    $('#assignUserId').val(userId);
    $('#assignRoleModalLabel').text(`为用户 ${userId} 分配角色`);

    // 填充角色下拉框
    const roleSelect = $('#roleSelect');
    roleSelect.empty();
    roleSelect.append('<option value="">请选择角色</option>');

    allRoles.forEach(role => {
      roleSelect.append(`<option value="${role.roleId}">${role.roleName}</option>`);
    });

    // 加载用户当前角色
    loadUserCurrentRole(userId);

    roleModal.show();
  }

  // 加载用户当前角色
  function loadUserCurrentRole(userId) {
    $.ajax({
      url: '/sysUser/getRoleByUserId',
      method: 'GET',
      data: { userId: userId },
      success: function(response) {
        const currentRoleDiv = $('#currentRole');
        currentRoleDiv.empty();

        if (response.success) {
          if (response.data) {
            // 查找角色名称
            const role = allRoles.find(r => r.roleId === response.data);
            currentRoleDiv.text(role ? role.roleName : '未知角色');
          } else {
            currentRoleDiv.text('未分配角色');
          }
        } else {
          currentRoleDiv.text('加载失败');
          showAlert('danger', response.message || '获取用户角色失败');
        }
      },
      error: function() {
        $('#currentRole').text('加载失败');
        showAlert('danger', '获取用户角色失败');
      }
    });
  }

  // 执行角色分配
  function assignRole() {
    const userId = $('#assignUserId').val();
    const roleId = $('#roleSelect').val();

    if (!roleId) {
      showAlert('danger', '请选择要分配的角色');
      return;
    }

    $.ajax({
      url: '/sysUser/assignRole',
      method: 'POST',
      data: {
        userId: userId,
        roleId: roleId
      },
      success: function(response) {
        if (response.success) {
          showAlert('success', '角色分配成功');
          loadUserCurrentRole(userId); // 刷新当前角色显示
          loadUsers(currentPage); // 刷新表格中的角色显示
        } else {
          showAlert('danger', response.message || '角色分配失败');
        }
      },
      error: function(xhr) {
        showAlert('danger', '请求失败: ' + (xhr.responseJSON?.message || xhr.statusText));
      }
    });
  }

  // 从表格中获取用户数据（临时方案）
  function getUserFromTable(userId) {
    const rows = $('#userTableBody tr');
    for (let i = 0; i < rows.length; i++) {
      const cells = rows[i].cells;
      if (parseInt(cells[0].textContent) === userId) {
        return {
          userId: parseInt(cells[0].textContent),
          userName: cells[1].textContent,
          pid: cells[2].textContent === '-' ? '' : cells[2].textContent,
          mobile: cells[3].textContent === '-' ? '' : cells[3].textContent,
          email: cells[4].textContent === '-' ? '' : cells[4].textContent,
          address: cells[5].textContent === '-' ? '' : cells[5].textContent
        };
      }
    }
    return null;
  }

  // 保存用户（新增或更新）
  function saveUser() {
    const userId = $('#userId').val();
    const password = $('#password').val();
    const confirmPassword = $('#confirmPassword').val();

    if (!userId && (password !== confirmPassword || !password)) {
      showAlert('danger', '请填写并确认密码');
      return;
    }
    if (userId && password && password !== confirmPassword) {
      showAlert('danger', '两次输入的密码不一致');
      return;
    }

    const user = {
      userId: userId ? parseInt(userId) : null,
      userName: $('#userName').val(),
      pid: $('#pid').val(),
      mobile: $('#mobile').val(),
      email: $('#email').val(),
      address: $('#address').val(),
      password: password || undefined
    };

    if (!user.userName) {
      showAlert('danger', '用户名不能为空');
      return;
    }

    const url = userId ? '/sysUser/updateUser' : '/sysUser/addUser';
    const method = userId ? 'PUT' : 'POST';

    $.ajax({
      url: url,
      method: method,
      contentType: 'application/json',
      data: JSON.stringify(user),
      success: function(response) {
        if (response.success) {
          showAlert('success', userId ? '用户更新成功' : '用户添加成功');
          userModal.hide();
          loadUsers(currentPage);
        } else {
          showAlert('danger', response.message || '操作失败');
        }
      },
      error: function(xhr) {
        showAlert('danger', '请求失败: ' + (xhr.responseJSON?.message || xhr.statusText));
      }
    });
  }

  // 确认删除用户
  function confirmDelete(userId) {
    if (confirm('确定要删除此用户吗？此操作不可恢复！')) {
      deleteUser(userId);
    }
  }

  // 删除用户
  function deleteUser(userId) {
    $.ajax({
      url: '/sysUser/deleteUser',
      method: 'DELETE',
      data: { userId: userId },
      success: function(response) {
        if (response.success) {
          showAlert('success', '用户删除成功');
          loadUsers(currentPage);
        } else {
          showAlert('danger', response.message || '用户删除失败');
        }
      },
      error: function() {
        showAlert('danger', '删除请求失败');
      }
    });
  }

  // 重置搜索条件
  function resetSearch() {
    $('#searchUserName').val('');
    loadUsers(1);
  }

  // 显示提示信息
  function showAlert(type, message) {
    const alert = $(`
      <div class="alert alert-${type} alert-dismissible fade show alert-message">
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    `);
    $('body').append(alert);
    setTimeout(() => alert.alert('close'), 3000);
  }
</script>
</body>
</html>
